package Hot_100;

import java.util.Scanner;

//接雨水
public class Hot_100_42 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //初始化数组
        int n = sc.nextInt();
        int arr[] = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        //调用处理函数并输出结果
        System.out.println(trap(arr));
    }

    /**
     * 求接多少雨水函数
     *
     * @param height
     * @return
     */
    public static int trap(int[] height) {
        int left = 0, right = height.length - 1;
        int l_max = 0, r_max = 0;
        int res = 0;
        while (left < right) {
            l_max = Math.max(l_max, height[left]);
            r_max = Math.max(r_max, height[right]);
            if (l_max < r_max) {
                res += (l_max - height[left]);
                left++;
            } else {
                res += (r_max - height[right]);
                right--;
            }
        }
        return res;
    }
}
//时间复杂度: O(n)
//空间复杂度: O(1)
